# /usr/bin/evn python
# -*- coding:utf-8 -*-

import pymysql

class MySQL(object):
    '''
    MySQL数据库操作基类
    '''

    __host__ = "192.168.149.62"
    __port__ = 3306
    __user__ = "mysql"
    __passwd__ = "mysql888"
    __db__ = "falcon_portal"
    __charset__ = 'utf8'

    def __init__(self, *args, **kwargs):
        self.conn_info = kwargs
        
        if not kwargs.get('host'):
            self.conn_info['host'] = self.__host__
        if not kwargs.get('port'):
            self.conn_info['port'] = self.__port__
        if not kwargs.get('user'):
            self.conn_info['user'] = self.__user__
        if not kwargs.get('passwd'):
            self.conn_info['passwd'] = self.__passwd__
        if not kwargs.get('db'):
            self.conn_info['db'] = self.__db__
        if not kwargs.get('charset'):
            self.conn_info['charset'] = self.__charset__

        self.conn = pymysql.connect(**self.conn_info)
        self.cur = self.conn.cursor()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.conn.commit()
        self.conn.close()

    def search(self, cmd, limit = False):
        self.cur.execute(cmd)
        if limit:
            result = self.cur.fetchone()
        else:
            result = self.cur.fetchall()
        return result

    def update(self, cmd):
        res = self.cur.execute(cmd)
        return res